package org.hefan.hrm.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.hefan.hrm.client.LoginUserClient;
import org.hefan.hrm.domain.Employee;
import org.hefan.hrm.domain.LoginUser;
import org.hefan.hrm.domain.Tenant;
import org.hefan.hrm.dto.TenantEnteringDto;
import org.hefan.hrm.exception.ErrorCode;
import org.hefan.hrm.exception.ValidUtil;
import org.hefan.hrm.mapper.EmployeeMapper;
import org.hefan.hrm.mapper.TenantMapper;
import org.hefan.hrm.query.TenantQuery;
import org.hefan.hrm.service.ITenantService;
import org.hefan.hrm.util.AjaxResult;
import org.hefan.hrm.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HeFan
 * @since 2022-01-02
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginUserClient loginUserClient;

    /**
     * 可以连表查询
     * @param query
     * @return PageList分页数据
     */
    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        // 封装page对象
        Page<Tenant> page = new Page<>(query.getPage(), query.getRows());
        // 查询当前页数据
        List<Tenant> datas = tenantMapper.loadPageList(page, query);
        return new PageList<>(page.getTotal(), datas);
    }

    /**
     * 店铺入驻
     * @param enteringDto 参数是从前端传来的dto
     */
    @Override
    public void entering(TenantEnteringDto enteringDto) {
        // 1 参数校验
        //1.1 null检验
        ValidUtil.assertNotNull(enteringDto.getMealId(), ErrorCode.CODE_400_MEAL_NOT_NULL);
        //1.2 判断租户是否已经存在
        // MybatisPlus封装的一个查询条件构造器 -- EntityWrapper
        EntityWrapper<Tenant> wrapper = new EntityWrapper<>();
        // 从前端获取到传来的租户
        Tenant tenant = enteringDto.getTenant();
        // 例子: eq("name", "老王") ---> name = '老王'
        // 此处是company_name = tenant.getCompanyName()
        // 翻译:如果属性company_name等于tenant.getCompanyName()
        wrapper.eq("company_name", tenant.getCompanyName());
        List<Tenant> list = tenantMapper.selectList(wrapper);
//        if (list != null && list.size() > 0)
//            throw new RuntimeException("租户已经入驻！直接登录!!!");
        ValidUtil.assertListIsNull(list, ErrorCode.CODE_400_TENANT_EXSIT);
        //1.3 管理员已经存在  方案1（采纳）：让他直接登录进去添加机构 方案2：进行密码比对，直接关联即可。
        Employee employee = enteringDto.getEmployee();
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>()
                .eq("username", employee.getUsername())
                .or()
                .eq("email", employee.getEmail())
                .or()
                .eq("tel", employee.getTel())
        );
//        if (employees != null && employees.size() > 0)
//            throw new RuntimeException("您已经入驻过店铺了！登录后可以添加新的店铺！");
        ValidUtil.assertListIsNull(employees, ErrorCode.CODE_400_ADMIN_EXSIT);

        //2 调用授权服务里面登录用户服务添加用户，并返回登录id
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setType(0);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
//        if (!ajaxResult.isSuccess()) // 失败
//            throw new RuntimeException(ajaxResult.getMessage());
        ValidUtil.assertTrue(ajaxResult.isSuccess(), ajaxResult.getMessage());

        Long loginUserId = Long.valueOf(ajaxResult.getResultObj().toString());
        //3 添加管理员
        employee.setLoginId(loginUserId);
        employeeMapper.insert(employee);
        //4 添加租户
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);
        //5 租户与套餐直接中间表
        // mybatis添加多个参数用map
        Map<String, Long> params = new HashMap<>();
        params.put("tenantId", tenant.getId());
        params.put("mealId", enteringDto.getMealId());
        tenantMapper.saveTenatMeals(params);
    }
}
